const WXAPI = require('apifm-wxapi')
const APP = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showMpjbutton: false,

    openShare: false,
    cardUserInfo: undefined,
    kActionType: {},
    content: '...',
    qrcode: undefined,
    focus: false,
    inputValue: '',
    pickerHidden: true,
    chosen: '',

    // findUser: false,
    submitInfo: '查找',
    findAction: false,
    showAdd: true,
    adminInfo: {
      adminIdcard: undefined,
      adminName: undefined,
      adminSex: undefined,
      adminAge: undefined
    },
    tmpImg: undefined,
    showImg: false
  },

  pickerConfirm(e) {
    this.setData({
      pickerHidden: true
    })
    this.setData({
      chosen: e.detail.value
    })
  },

  pickerCancel() {
    this.setData({
      pickerHidden: true
    })
  },

  pickerShow() {
    this.setData({
      pickerHidden: false
    })
  },

  addAdmin() {
    this.setData({
      showAdd: false,
      findAction: true,
      submitInfo: '添加并上传'
    })
  },

  checkInfo() {
    let info = this.data.adminInfo
    // todo 图片校验
    let ifOk = info.adminIdcard && info.adminName && info.adminName && info.adminSex && this.data.tmpImg
    return ifOk
  },

  createImg() { // 生成海报
    wx.chooseImage({
      count: 1,
      success: (res) => {
        console.log(res)
        // wx.setStorageSync('_tongueImg', res.tempFilePaths[0])
        this.setData({tmpImg: res.tempFilePaths[0], showImg: true})
      }
    })
  },

  async formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let that = this
    if(this.data.submitInfo === '查找') {
      if(!e.detail.value.adminIdcard) return
      console.log('调用findByIdcard')
      await WXAPI.findByIdcard(e.detail.value).then(function (res) {
        if (res.message !== 'error') {
          // 如果找到
          console.log(res.result)
          if (res.result !== null) {
            let admin = res.result
            console.log(admin)
            that.setData({adminInfo:{
                adminIdcard: admin.adminIdcard,
                adminName: admin.adminName,
                adminSex: admin.adminSex,
                adminAge: admin.adminAge
              }})
            that.setData({showAdd: false, submitInfo: '提交', findAction: true})
          } else {
            wx.showToast({
              title: '没有该人员',
              icon: 'error',
              duration: 2000
            })
          }
        } else {
          console.log(res)
        }
      })
    } else if(this.data.submitInfo === '提交' || this.data.submitInfo === '添加并上传') {
      if(this.checkInfo()) {
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '请完善信息',
          icon: 'error',
          duration: 2000
        })
      }
    }
    // this.$forceUpdate()
    // console.log('res')
  },

  formReset(e) {
    console.log('form发生了reset事件，携带数据为：', e.detail.value)
    this.setData({
      chosen: '',
      submitInfo: '查找',
      findAction: false,
      showAdd: true,
      tmpImg: undefined,
      showImg: false,
      adminInfo: {
        adminIdcard: undefined,
        adminName: undefined,
        adminSex: undefined,
        adminAge: undefined
      }
    })
  },

  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  bindReplaceInput: function (e) {
    var value = e.detail.value
    var pos = e.detail.cursor
    var left
    if (pos !== -1) {
      // 光标在中间
      left = e.detail.value.slice(0, pos)
      // 计算光标的位置
      pos = left.replace(/11/g, '2').length
    }

    // 直接返回对象，可以对输入进行过滤处理，同时可以控制光标的位置
    return {
      value: value.replace(/11/g, '2'),
      cursor: pos
    }

    // 或者直接返回字符串,光标在最后边
    // return value.replace(/11/g,'2'),
  },
  bindHideKeyboard: function (e) {
    if (e.detail.value === '123') {
      // 收起键盘
      wx.hideKeyboard()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    if (e.scene) { // 扫码
      const scene = decodeURIComponent(e.scene)
      wx.setStorageSync('referrer', scene)
      APP.globalData.cardUid = scene
    }
    setTimeout(() => {
      this.showNickPOP()
    }, 3000);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow () {
    // await WXAPI.queryConfigBatch('mallName,DEFAULT_FRIEND_UID').then(async function (res) {
    //   if (res.code == 0) {
    //     res.data.forEach(config => {
    //       wx.setStorageSync(config.key, config.value);
    //     })
    //   }
    // })
    // test
    await WXAPI.test().then(function (res) {
      console.log(res)
    })

    const cardUid = await this.getCardUid()
    this.getCardInfo(cardUid)
    const qrcode = APP.globalData._haibaoimg_qrcode
    if (!qrcode) {
      // 获取二维码
      // WXAPI.wxaQrcode({
      //   scene: cardUid,
      //   page: 'pages/card/main',
      //   is_hyaline: false,
      //   expireHours: 1,
      //   autoColor: true
      // }).then(res => {
      //   if(res.code == 0){
      //     APP.globalData._haibaoimg_qrcode = res.data
      //     this.setData({
      //       qrcode: res.data
      //     })
      //   }
      // })
    } else {
      this.setData({
        qrcode
      })
    }
    this.setData({
      cardUid,
      uid: wx.getStorageSync('uid')
    })
  },
  async getCardUid(){
    let cardUid = APP.globalData.cardUid
    const uid = wx.getStorageSync('uid')
    if (!cardUid) {
      // 没有通过链接或者扫码进来
      if (uid) {
        // 当前用户已登录
        // const res = await WXAPI.userDetail(wx.getStorageSync('token'))
        // if (res.code == 0 && res.data.userLevel && res.data.userLevel.name === 'aicard') {
        //   return uid
        // }
      }
      // 读取默认设置
      cardUid = wx.getStorageSync('DEFAULT_FRIEND_UID')
    }    
    return cardUid
  },
  async getCardInfo(cardUid){
    const uid = wx.getStorageSync('uid')
    const token = wx.getStorageSync('token')
    if (uid) {
      // 添加到我的名片夹
      // WXAPI.addFriend(token, cardUid)
    }
    // 读取名片详情信息
    // const res = await WXAPI.friendUserDetail(token, cardUid)
    // if (res.code == 0) {
    //   const _data = {
    //     kActionType: {}
    //   }
    //   if (res.data.userLevel && res.data.userLevel.maxUser && res.data.userLevel.maxUser > 1) {
    //     _data.showMpjbutton = true
    //   }
    //   _data.cardUserInfo = res.data
    //   if (_data.cardUserInfo.ext) {
    //     Object.keys(_data.cardUserInfo.ext).forEach(k => {
    //       // kActionType
    //       const v = _data.cardUserInfo.ext[k]
    //       _data.kActionType[k] = v
    //     })
    //   }
    //   wx.setNavigationBarTitle({
    //     title: _data.cardUserInfo.base.nick + ' - ' + wx.getStorageSync('mallName')
    //   })
    //   this.setData(_data)
    // }
  },
  onShareAppMessage: function () {
    return {
      title: '您好，我是 ' + wx.getStorageSync('mallName') + ' 的' + this.data.cardUserInfo.base.nick + '，请惠存我的名片。',
      path: '/pages/card/main?cardUid=' + this.data.cardUserInfo.base.id,
      imageUrl: this.data.cardUserInfo.base.avatarUrl
    }
  },
  onShareTimeline() {    
    return {
      title: '您好，我是 ' + wx.getStorageSync('mallName') + ' 的' + this.data.cardUserInfo.base.nick + '，请惠存我的名片。',
      query: 'cardUid=' + this.data.cardUserInfo.base.id,
      imageUrl: this.data.cardUserInfo.base.avatarUrl
    }
  },
  callPhone(){
    wx.makePhoneCall({
      phoneNumber: this.data.cardUserInfo.base.mobile
    })
  },
  copyData(e){
    const v = e.currentTarget.dataset.v
    wx.setClipboardData({
      data: v,
      success: (res) => {
        wx.showToast({
          title: '复制成功',
          icon: 'success'
        })
      }
    })
  },
  goIndex(){
    wx.navigateTo({
      url: '/pages/index/main'
    })
  },
  createHaibao() { // 生成海报
    wx.chooseImage({
      count: 1,
      success: (res) => {
        console.log(res)
        // wx.setStorageSync('_tongueImg', res.tempFilePaths[0])
        // this.cardposter()
      }
    })
  },
  cardposter() {
    wx.navigateTo({ 
        url: '/pages/cardposter/main?cardUid=' + this.data.cardUserInfo.base.id
    })
  },
  addPhoneContact() {
    // 调用登录接口
    wx.addPhoneContact({
      photoFilePath: this.data.cardUserInfo.base.avatarUrl,
      organization: wx.getStorageSync('mallName'),
      title: this.data.cardUserInfo.ext['职位'],
      firstName: this.data.cardUserInfo.base.nick,
      mobilePhoneNumber: this.data.cardUserInfo.base.mobile
    })
  },
  async showNickPOP() {
    // const res = await WXAPI.userDetail(wx.getStorageSync('token'))
    // if (res.code == 0 && (!res.data.base.nick || !res.data.base.avatarUrl)) {
    //   this.setData({
    //     nickPopShow: true,
    //     popnick: res.data.base.nick ? res.data.base.nick : '',
    //     popavatarUrl: res.data.base.avatarUrl ? res.data.base.avatarUrl : '',
    //   })
    // }
  },
})